package com.servlet;

import com.alibaba.fastjson.JSONObject;
import com.entity.CommonResult;
import com.entity.PageData;
import com.entity.Student;
import com.mysql.cj.util.StringUtils;
import com.service.IStudentService;
import com.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/StudentServlet/*")
public class StudentServlet extends HttpServlet {
    private IStudentService studentService = new StudentServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求方法
        String uri = req.getRequestURI();
        String process = uri.substring(uri.lastIndexOf("/")+1);

        System.out.println("proccess:"+process);

//        //设置响应编码
//        resp.setContentType("text/html;charset=utf-8");

        //定义处理之后返回的数据对象
        Object data = null;

        switch (process){
            case "query":
                data = this.query(req,resp);
                break;
            case "queryByPage":
                data = this.queryByPage(req,resp);
                break;
            case "queryForLayUI":
                data = this.queryForLayUI(req,resp);
                break;
            case "add":
                data=this.add(req,resp);
                break;
            case "update":
                data = this.update(req,resp);
                break;
            case "del":
                data = this.del(req,resp);
                break;
        }

        System.out.println("data:"+data);
        //将数据转为json字符串
        String jsonStr = JSONObject.toJSONStringWithDateFormat(data,"yyyy-MM-dd");
        System.out.println(jsonStr);
        PrintWriter out = resp.getWriter(); //获取输出流对象
        out.println(jsonStr); //输出json字符串给浏览器
        out.flush(); //清空缓存
        out.close();//关闭流对象
    }

    //根据id删除
    private Object del(HttpServletRequest req, HttpServletResponse resp) {
        String ids = req.getParameter("ids");
        int count = studentService.delete(ids);
        if (count>0){
            return CommonResult.success();
        }else{
            return CommonResult.fail();
        }
    }


    private Object queryForLayUI(HttpServletRequest req, HttpServletResponse resp) {
        //获取前端传入的分页参数
        String pageNo = req.getParameter("page");
        String pageSize = req.getParameter("limit");
        //判断参数是否有效
        Integer pn = StringUtils.isNullOrEmpty(pageNo)?1:Integer.parseInt(pageNo);
        Integer ps = StringUtils.isNullOrEmpty(pageSize)?3:Integer.parseInt(pageSize);

        PageData pd =  studentService.queryByPage(pn,ps);

        return new CommonResult(0,"success",pd.getTotalCount(),pd.getData());
    }

    private Object queryByPage(HttpServletRequest req, HttpServletResponse resp) {
        //获取前端传入的分页参数
        String pageNo = req.getParameter("pageNo");
        String pageSize = req.getParameter("pageSize");
        //判断参数是否有效
        Integer pn = StringUtils.isNullOrEmpty(pageNo)?1:Integer.parseInt(pageNo);
        Integer ps = StringUtils.isNullOrEmpty(pageSize)?3:Integer.parseInt(pageSize);

        return studentService.queryByPage(pn,ps);
    }

    private Object update(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("111");
        //获取传入的数据
        Integer studentId = Integer.parseInt(req.getParameter("studentId"));
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        Date birthday = java.sql.Date.valueOf(req.getParameter("birthday"));
        String province = req.getParameter("province");
        Integer classId = Integer.parseInt(req.getParameter("classId"));

        //封装实体对象
        Student student = new Student(
                studentId,name,sex,birthday,province,classId
        );

        //调用业务层保存数据
        int count = studentService.update(student);
        System.out.println("count:"+count);

        //定义结果数据
        Map<String,Object> res = new HashMap<>();
        //添加成功
        if(count==1){
            //code为0说明处理成功
            res.put("code",0);
        }else{
            //code为1处理失败
            res.put("code",1);
        }
        System.out.println("res:"+res);
        return res;
    }

    //添加
    private Object add(HttpServletRequest req, HttpServletResponse resp) {
        //获取传入的数据
        String name=req.getParameter("name");
        String sex=req.getParameter("sex");
        Date birthday=java.sql.Date.valueOf(req.getParameter("birthday"));
        String province=req.getParameter("province");
        Integer classId=Integer.parseInt(req.getParameter("classId"));

        //封装实体对象
        Student student=new Student(
                name,sex,birthday,province,classId
        );

        //调用业务层保存数据
        int count= studentService.add(student);

        //定义数据结果
        Map<String,Object> res=new HashMap<>();
        //添加成功
        if(count==1){
            //code为0说明处理成功
            res.put("code",0);
        }else{
            //code为1处理失败x`
            res.put("code",1);
        }
        return res;

    }

    /**
     * 执行查询
     * @param req
     * @param resp
     * @return
     */
    private Object query(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("=====StudentServlet query=======");
        return studentService.listAll();
    }
}
